package com.kingbook.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

import java.util.List;

import static org.apache.poi.ss.usermodel.BorderStyle.THIN;
import static org.apache.poi.ss.usermodel.FillPatternType.SOLID_FOREGROUND;
import static org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER;
import static org.apache.poi.ss.usermodel.HorizontalAlignment.LEFT;

public class ExeclUitl {


    public HSSFWorkbook writeExecls(String label, List<ExeclTitle> titles, JSONArray array) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet(label);
        //创建文档信息
        workbook.createInformationProperties();
        DocumentSummaryInformation documentSummaryInformation = workbook.getDocumentSummaryInformation();
        documentSummaryInformation.setManager("刘德华");//管理者
        documentSummaryInformation.setCompany("宁波重大起吊公司");//公司
        documentSummaryInformation.setCategory("工单明细表");//类别
        //标题
        HSSFRow labelRow = sheet.createRow(0);
        labelRow.setHeightInPoints(50);
        HSSFCell cell = labelRow.createCell(0);
        cell.setCellValue(label);
        cell.setCellStyle(getLabelStyle(workbook));
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, titles.size() - 1);
        sheet.addMergedRegion(region);
//        RegionUtil.setBorderTop(THIN, region, sheet);
//        RegionUtil.setBorderBottom(THIN, region, sheet);
//        RegionUtil.setBorderLeft(THIN, region, sheet);
//        RegionUtil.setBorderRight(THIN, region, sheet);
        //表头信息
        HSSFCellStyle titleStyle = getTitleStyle(workbook);
        HSSFRow titleRow = sheet.createRow(1);
        titleRow.setHeightInPoints(20);
        int i = 0;
        for (ExeclTitle t : titles) {
            cell = titleRow.createCell(i);
            cell.setCellValue(t.getTitle());
            cell.setCellStyle(titleStyle);
            sheet.setColumnWidth(i, t.getColumnWidth());
            i++;
        }
        //数据
        JSONObject json;
        String value;
        HSSFCellStyle style = getDataStyle(workbook);
        HSSFCellStyle styleLeft = getDataStyle(workbook);
        styleLeft.setAlignment(LEFT);
        for (i = 0; i < array.size(); i++) {
            HSSFRow row = sheet.createRow(i + 2);
            json = array.getJSONObject(i);
            int k = 0;
            boolean wrap = false;
            for (ExeclTitle t : titles) {
                value = json.getString(t.getKey()).trim();
                cell = row.createCell(k++);
                cell.setCellValue(value);
                cell.setCellStyle(t.getAlign() == CENTER ? style : styleLeft);
                cell.setCellType(CellType.STRING);
                wrap = wrap || value.getBytes().length > (t.getWords() / 2) * 3;    //word中一个中文2位，byte一个中文占3位
            }
            System.out.println("-->" + i);
            if (!wrap)
                row.setHeightInPoints(20);
        }

        HSSFPrintSetup ps = sheet.getPrintSetup();
        ps.setLandscape(false); // 打印方向，true：横向，false：纵向
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE); //纸张
        sheet.setMargin(HSSFSheet.TopMargin, (double) 0.5);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (double) 0.5);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (double) 0.3);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (double) 0.28);// 页边距（右）
        sheet.setHorizontallyCenter(true);//设置打印页面为水平居中
//        sheet.setVerticallyCenter(true);//设置打印页面为垂直居中
        sheet.setDisplayGridlines(false);
        sheet.setGridsPrinted(true);
        return workbook;
    }

    private HSSFCellStyle getLabelStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setAlignment(CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
//        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_TURQUOISE.getIndex());
//        style.setFillPattern(SOLID_FOREGROUND);
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//        font.setFontHeightInPoints((short) 10);
        font.setFontHeight((short) 400);
        font.setFontName("黑体");
        style.setFont(font);
        return style;
    }

    private HSSFCellStyle getTitleStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setAlignment(CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        // 背景色
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.LIGHT_YELLOW.getIndex());
        style.setFillPattern(SOLID_FOREGROUND);
        // 设置边框
        style.setBorderBottom(THIN);
        style.setBorderLeft(THIN);
        style.setBorderRight(THIN);
        style.setBorderTop(THIN);
        // 自动换行
        style.setWrapText(false);

        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        font.setFontHeightInPoints((short) 4);
        font.setFontHeight((short) 200);
        font.setFontName("黑体");
        font.setBold(true);
        style.setFont(font);
        return style;
    }

    private HSSFCellStyle getDataStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setAlignment(CENTER);//水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        // 设置边框
        style.setBorderBottom(THIN);
        style.setBorderLeft(THIN);
        style.setBorderRight(THIN);
        style.setBorderTop(THIN);
        // 自动换行
        style.setWrapText(true);
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        font.setFontName("黑体");
        style.setFont(font);
        return style;
    }

    public ExeclTitle createExeclTitle(String key, String title, int words, HorizontalAlignment align) {
        return new ExeclTitle(key, title, words, align);
    }

    public class ExeclTitle {
        String key;
        String title;
        int words;
        HorizontalAlignment align;

        ExeclTitle(String key, String title, int words, HorizontalAlignment align) {
            this.key = key;
            this.title = title;
            this.words = words;
            this.align = align;
        }

        String getKey() {
            return key;
        }

        String getTitle() {
            return title;
        }

        /**
         * Execl cell 以一个字符的1/256的宽度作为一个单位
         * 字符数*256
         */
        int getColumnWidth() {
            return words * 256;
        }

        int getWords() {
            return words;
        }

        HorizontalAlignment getAlign() {
            return align;
        }
    }

}
